package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.SaleOutItemMapper;
import cn.wolfcode.crm.mapper.SaleOutMapper;
import cn.wolfcode.crm.mapper.ProductStockMapper;
import cn.wolfcode.crm.query.SaleOutQueryObject;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.ISaleOutService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class SaleOutServiceImpl implements ISaleOutService {
    @Autowired
    private SaleOutMapper saleOutMapper;
    @Autowired
    private SaleOutItemMapper saleOutItemMapper;
    @Autowired
    private ProductStockMapper productStockMapper;

    public SaleOut selectByPrimaryKey(Long id) {
        return saleOutMapper.selectByPrimaryKey(id);
    }

    public List<SaleOut> selectAll() {
        return saleOutMapper.selectAll();
    }


    public PageResult query(SaleOutQueryObject qo) {
        int total = saleOutMapper.selectCount(qo);
        if(total==0){
            return new PageResult(total, Collections.EMPTY_LIST);
        }
        List<SaleOut> rows = saleOutMapper.queryForList(qo);
        return new PageResult(total,rows);
    }

    public void saveOrUpdate(SaleOut order) {
        if (order.getId() == null) {
            save(order);
        }else {
            update(order);
        }

    }


    //新增订单
    private void save(SaleOut order) {
        order.setInputUser(UserContext.getCurrentUser());
        order.setInputTime(new Date());
        order.setStatus(SaleOut.NORMAL);
        BigDecimal totaNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        //保存订单的明细
        for (SaleOutItem item : order.getItems()) {
            BigDecimal costPrice = item.getSalePrice();
            BigDecimal number = item.getNumber();
            BigDecimal amout = costPrice.multiply(number).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amout);
            totalAmount = totalAmount.add(amout);
            totaNumber = totaNumber.add(number);
        }
        order.setTotalAmount(totalAmount);
        order.setTotalNumber(totaNumber);
        //保存单据
        saleOutMapper.insert(order);
        //保存明细
        for (SaleOutItem item : order.getItems()) {
            item.setOutId(order.getId());
            saleOutItemMapper.insert(item);
        }
    }
    //编辑订单
    private void update(SaleOut order) {

    }

    //修改状态
    @Override
    public void audit(Long id) {
        SaleOut saleOut = saleOutMapper.selectByPrimaryKey(id);
        // 检查当前单据的状态，未审核才能审核
        if (saleOut.getStatus() == StockOutcomeBill.NORMAL) {
            //获取单据的仓库
            Depot depot = saleOut.getDepot();
            for (SaleOutItem item : saleOut.getItems()) {
                Product p = item.getProduct();
                ProductStock ps = productStockMapper.selectStockByprotIdAndDepotId(p.getId(), depot.getId());
                if (ps == null) {
                    String msg = "仓库:["+depot.getName()+"]没有["+p.getName()+"]商品的库存了;";
                    throw new RuntimeException(msg);
                }
                if(item.getNumber().compareTo(ps.getStoreNumber()) > 0){
                    String msg = "仓库["+depot.getName()+p.getName()+"]商品的库存是："+ps.getStoreNumber()+",不足出库数量:"+item.getNumber();
                    throw new RuntimeException(msg);
                }
                BigDecimal am = ps.getPrice().multiply(item.getNumber()).setScale(2, RoundingMode.HALF_UP);
                BigDecimal amount = ps.getAmount().subtract(am);
                ps.setAmount(amount);
                BigDecimal num = ps.getStoreNumber().subtract(item.getNumber());
                ps.setStoreNumber(num);
                productStockMapper.updateByPrimaryKey(ps);
                //记账
                SaleAccount sa = new SaleAccount();
                sa.setVdate(new Date());
                sa.setNumber(num);
                sa.setCostPrice(ps.getPrice());
                sa.setCostAmount(am);
                sa.setSalePrice(item.getSalePrice());
                sa.setSaleAmount(item.getSalePrice().multiply(item.getNumber()).setScale(2,RoundingMode.HALF_UP));
                sa.setProduct(p);
                sa.setEmployee(UserContext.getCurrentUser());
                sa.setClient(saleOut.getClient());

            }
            //设置单据的审核人，时间，状态
            saleOut.setAuditor(UserContext.getCurrentUser());
            saleOut.setAuditTime(new Date());
            saleOut.setStatus(StockOutcomeBill.AUDIT);
            saleOutMapper.audit(saleOut);
        }
    }
}
